package com.vmladenov.cook.ui.user;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.vmladenov.cook.R;
import com.vmladenov.cook.core.DialogHelper;
import com.vmladenov.cook.core.db.UserServiceHelper;
import com.vmladenov.cook.ui.MainActivity;

public final class RegisterActivity extends Activity
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_user_screen);
	}

	public void onRegister(View v)
	{
		EditText tbUserName = (EditText) findViewById(R.id.tbUserName);
		EditText tbPassWord = (EditText) findViewById(R.id.tbPassword);
		EditText tbConfirmPassWord = (EditText) findViewById(R.id.tbConfirmPassword);
		EditText tbEMail = (EditText) findViewById(R.id.tbEMail);

		String password = tbPassWord.getText().toString();
		String confirmPassword = tbConfirmPassWord.getText().toString();
		String userName = tbUserName.getText().toString().trim();
		if (!password.equals(confirmPassword))
		{
			DialogHelper.showErrorDialog(this, getString(R.string.confirmPasswordNotEqual));
			return;
		}

		UserServiceHelper userServiceHelper = new UserServiceHelper();

		String res = userServiceHelper.registerUser(userName, password, tbEMail.getText().toString());
		if (res != "")
		{
			DialogHelper.showErrorDialog(this, res);
			return;
		}
		else
		{
			long userId = userServiceHelper.loginUser(userName, password);
			SharedPreferences preferences = getSharedPreferences("MandjaSettings", MODE_PRIVATE);
			Editor editor = preferences.edit();
			editor.putLong("UserId", userId);
			editor.putString("UserName", userName);
			editor.commit();
			Intent intent = new Intent();
			intent.setClass(RegisterActivity.this, MainActivity.class);
			startActivity(intent);
		}
	}

}
